//
//  YAPicBrowserAnimator.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/16.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SDWebImage
class YAPicBrowserAnimator: NSObject, UIViewControllerTransitioningDelegate {
     //MARK:--- 标识是展现出来还是展现回去
    var isPresented = false
 //MARK:--- 展现的起始位置
    var fromRect = CGRectZero
     //MARK:--- 展现的目标位置
    var toRect = CGRectZero
     //MARK:--- 展现的图片URL
    var url:NSURL?
     //动画播放的图像视图
    lazy var imageView:YAProgressView = {
        let iv = YAProgressView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true//原图显示，多余切掉
        //iv.sizeToFit()
        return iv
    }()
    
    //MARK:点中cell的的索引
    var cellCurrentIndex:NSIndexPath?
     //MARK:--- 接收准备参数
    weak var picView:YAStatusPictureView?
    func prepareAnimator(picView:YAStatusPictureView,fromRect:CGRect,toRect:CGRect,url:NSURL){
        self.picView = picView
        self.fromRect = fromRect
        self.imageView.frame = fromRect
        self.toRect = toRect
        self.url = url
    }
     //MARK:--- 返回提供展现 present 转场动画对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
     //MARK:--- 返回提供接触 dismiss 转场动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        
        isPresented = false
        
        return self
    }
}
// MARK: 转场动画协议 专门提供转场动画的实现细节(包括显示出来和退回去)
extension YAPicBrowserAnimator:UIViewControllerAnimatedTransitioning{
     //MARK:--- 返回转场所需要的时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2
    }
     //MARK:--- 设置转场动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        //拿到源控制器
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        //拿到目的控制器
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        
        print(fromVC,toVC)
        isPresented ? presentAnim(transitionContext):dismissAnim(transitionContext)
    }
    private func presentAnim(transitionContext: UIViewControllerContextTransitioning){
        //一开始是对控制器的View做了手脚，现在用容器视图
        transitionContext.containerView()?.addSubview(imageView)
        imageView.frame = fromRect
        imageView.sd_setImageWithURL(url, placeholderImage: nil, options: .RetryFailed, progress: { (current, total) -> Void in
            self.imageView.progress = CGFloat(current)/CGFloat(total)
            }) { (_,error,_, _) -> Void in
                if error != nil {
                    printLog(error,logError:true)
                    transitionContext.completeTransition(false)
                    return
                }
                //3.图像下载完成之后，再显示动画
                UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in
                    self.imageView.frame = self.toRect
                    }, completion: { (_) -> Void in
                        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
                        transitionContext.containerView()?.addSubview(toView)
                        //self.imageView = nil
                        self.imageView.removeFromSuperview()
                        
                        transitionContext.completeTransition(true)
                })
        }
        
    }
    private func dismissAnim(transitionContext: UIViewControllerContextTransitioning){
      //拿到照片浏览器的控制器
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! YAPicBrowserController
        //通过浏览器视图获得内部的imageView和当前索引
        let imageView = fromVC.currentImageView
        let indexPath = fromVC.currentImageIndex
      //拿到正在展现的视图，并将其移除
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        fromView.removeFromSuperview()//这个不是fromVC的View么？
      //将图片添加到容器视图中
        transitionContext.containerView()?.addSubview(imageView)
        //设置图片位置为当前显示的位置?
        imageView.center = fromView.center
        //将fromVC的View的缩放形变添加到imageView上???
        let scale = fromVC.view.transform.a
        imageView.transform = CGAffineTransformScale(imageView.transform, scale, scale)
        imageView.alpha = scale
        
        //动画消失
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            //以下代码是考虑的在浏览器中滑动到了其他图片，此时就要重新计算返回位置
            imageView.frame = self.picView!.screenRect(indexPath)
            imageView.alpha = 1.0
            }) { (_) -> Void in
                imageView.removeFromSuperview()
                transitionContext.completeTransition(true)
        }
        
    }
    
}